package api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import domain.Product;
import exception.ProductException;
import service.ProductService;
import utils.GetRequestJsonUtils;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class GetBooksServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        约定参数格式：{category:"计算机"},则查询计算机的所有图书，为all查询所有图书
        JSONObject object=null;
        String category=null;
        Response build=null;
        try {
            object = GetRequestJsonUtils.getRequestJsonObject(req);
            category=object.getString("category");
        }catch (Exception e){
            e.printStackTrace();
            build=Response.build(ResponseCode.ERROR_PARAM);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(JSON.toJSON(build).toString());
            return;
        }
        ProductService productService=new ProductService();
        List<Product> list=null;
        if(category.equals("all")){//如果参数为all,查询所有书籍
            try {
                list=productService.listAll();
                build=Response.build(ResponseCode.SUCCESS,list);
            }catch (ProductException e){
                build=Response.build(e.getResponseCode());
            }
        }else{
            try {
                list=productService.findProductByCategory(category);
                build=Response.build(ResponseCode.SUCCESS,list);
            }catch (ProductException e){
                build=Response.build(e.getResponseCode());
            }
        }
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSON(build).toString());
    }
}
